<template style="background-color: #eef2f5;">
  <div class="app-container" >
    <!-- 父组件模板中 -->
    <div style="position: absolute; left: -9999px;">
      <report-page
        ref="reportComponent"
        @data-ready="onDataReady"
        @rendered="onRendered"
      ></report-page>
    </div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="量表名" prop="scaleName">
        <el-input
          v-model="queryParams.scaleName"
          placeholder="请输入量表名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="病患名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入病患名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dcp:screen:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dcp:screen:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dcp:screen:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="screenList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="量表名称" align="center" prop="scaleName" />
      <el-table-column label="病患名" align="center" prop="patientName" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="填表时间" align="center" prop="updateTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === '未完成'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="evaluation(scope.row)"
            v-hasPermi="['dcp:screen:edit']"
          >测评</el-button>
          <el-button
            v-if="scope.row.status === '已完成'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="examine(scope.row)"
            v-hasPermi="['dcp:screen:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dcp:screen:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="toSignIndex(scope.row)"
            v-if="scope.row.status === '已完成'"
          >签名</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="download(scope.row)"
            v-if="scope.row.remark != null && scope.row.remark != '' "
          >下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改量表筛选对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="量表名称" prop="scaleId">
          <el-select v-model="form.scaleId" filterable placeholder="请选择" :filter-method="selectScales">
            <el-option
              v-for="item in scaleBox"
              :key="item.scaleId"
              :label="item.scaleName"
              :value="item.scaleId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="病患名" prop="patientId">
          <el-select v-model="form.patientId" filterable placeholder="请选择" :filter-method="selectPatient">
            <el-option
              v-for="item in patientBox"
              :key="item.patientId"
              :label="item.childName"
              :value="item.patientId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 签名确认弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%">
      <span>是否要生成签名报告?</span>

      <el-form ref="form" :model="photoForm" :rules="rules" label-width="80px" style="margin-top: 20px">
        <el-form-item label="选择照片" prop="photo">
          <el-select
            v-model="photoForm.selectedPhoto"
            placeholder="请选择照片"
            @change="handlePhotoChange"
            clearable
          >
            <el-option
              v-for="item in photoOptions"
              :key="item.signId"
              :label="item.nickName"
              :value="item.image"
            >
              <div style="display: flex; align-items: center;">
                <img :src="item.image" style="width: 30px; height: 30px; margin-right: 10px;">
                <span>{{ item.nickName }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 显示选中的照片预览 -->
        <div v-if="photoForm.selectedPhotoUrl" style="margin-top: 20px;">
          <img :src="photoForm.selectedPhotoUrl" style="max-width: 100%; max-height: 300px;">
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="generateReport">取 消</el-button>
        <el-button type="primary" @click="generateReport">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 缩略图展示弹窗 -->
    <el-dialog
      title="签名报告预览"
      :visible.sync="reportDialogVisible"
      width="70%"
      v-loading="generatingReport">
      <div class="preview-container">
        <img :src="reportImageUrl" v-if="reportImageUrl" class="thumbnail-img">
        <div v-else>报告生成中...</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="quXiao">关 闭</el-button>
        <el-button
          type="primary"
          @click="downloadReport"
          :disabled="!reportImageUrl">
          下载报告
        </el-button>
      </span>
    </el-dialog>

    <!-- 隐藏的子组件（用于渲染但不显示） -->
    <div style="position: absolute; left: -9999px;">
      <report-page ref="reportComponent"></report-page>
    </div>
  </div>
</template>

<script>
import {listScreen, getScreen, delScreen, addScreen, updateScreen, insterScreen, uploadPhoto} from "@/api/dcp/screen";
import {listScales} from "@/api/dcp/scale";
import {listPatients} from "@/api/dcp/patient";
import html2canvas from 'html2canvas';
import ReportPage from '@/views/dcp/demo/ResultForm';
import {listHospital} from "@/api/dcp/hospital"
import {getSignList} from "@/api/dcp/sign";
import {getInfo} from "@/api/login";
import {uploadAvatar} from "@/api/system/user";
import store from "@/store";
export default {
  components: { ReportPage  },
  name: "Screen",
  data() {
    return {
      formData:'',
      userId:'',
      hospitalName:"",
      logo:"",
      photoForm:{
        selectedPhoto: '', // 选中的照片值
        selectedPhotoUrl: ''         // 选中的照片URL
      },
      photoOptions: [],
      scaleBox:[],
      patientBox:[],
      sca: [],
      pat: [],
      scales: [],
      patients: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 量表筛选表格数据
      screenList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scaleId: null,
        scaleName: null,
        patientId: null,
        patientName: null,
        status: null,
        result: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      dialogVisible2:false,
      options: [],
      value: '',
      thumbnailUrl:'',
      dialogVisible: false,
      reportDialogVisible: false,
      generatingReport: false,
      reportImageUrl: '',
      currentScaleScreenId: null,
      isDataReady: false,
      isRendered: false
    };
  },
  created() {
    this.getUser();
    this.getHospital()
    this.getList();
    console.log("refresh",this.$route.query.refresh)
    this.$on('refresh-list', this.getList);
  },
  beforeDestroy() {
    this.$off('refresh-list', this.getList);
  },
  methods: {
    quXiao(){
      this.getList();
      this.reportDialogVisible = false
    },
    //下载图片
    download(row){
      const link = document.createElement('a');
      link.href = process.env.VUE_APP_BASE_API +row.remark;
      link.download = `儿童行为量表报告_${row.scaleScreenId}.png`; // 设置下载的文件名
      link.click(); // 模拟点击下载
    },
    //获取当前用户信息
    getUser(){
      getInfo().then(res=>{
        this.userId = res.user.userId;
      })
    },
    //查询医院的名字和logo
    getHospital(){
      listHospital().then(res=>{
        console.log(res)
        this.hospitalName = res.rows[0].hospitalName
        this.logo = res.rows[0].logo
        console.log(this.hospitalName)
        console.log(this.logo)
      })
    },
    //查询签名照片
    getPhoto(){
      //是否需要获取当前医生id
      getSignList(this.userId).then(res=>{
        console.log(res.rows)
        this.photoOptions = res.rows
        for (let i = 0; i < this.photoOptions.length; i++) {
          var pho = this.photoOptions[i].image
          this.photoOptions[i].image =  process.env.VUE_APP_BASE_API + pho
        }
      })
    },
    //签名照片选择
    handlePhotoChange(val) {
      const selected = this.photoOptions.find(item => item.image === val);
      this.photoForm.selectedPhotoUrl = selected ?
        selected.image :
        '';
    },
    // 开始生成报告
    async startGenerateReport() {
      this.dialogVisible = false;
      this.reportDialogVisible = true;
      this.generatingReport = true;
      this.isDataReady = false;
      this.isRendered = false;
      try {
        // 触发子组件加载数据
        await this.$refs.reportComponent.loadData(this.currentScaleScreenId);
        // 等待数据和渲染完成
        await this.waitForDataAndRender();
        // 生成缩略图
        await this.generateThumbnail();
      } catch (error) {
        console.error('生成报告失败:', error);
        this.$message.error('生成报告失败: ' + error.message);
      } finally {
        this.generatingReport = false;
      }
    },
    // 生成缩略图（修改后的版本：签名在右下角，医院名字和logo在左上角）
    async generateThumbnail() {
      const reportCanvas = await html2canvas(this.$refs.reportComponent.$el, {
        scale: 0.8,
        useCORS: true,
        backgroundColor: '#fff',
        logging: true
      });

      // 创建新的 canvas 用于组合图片
      const combinedCanvas = document.createElement('canvas');
      const ctx = combinedCanvas.getContext('2d');

      // 设置新 canvas 的尺寸与报告缩略图相同
      combinedCanvas.width = reportCanvas.width;
      combinedCanvas.height = reportCanvas.height;

      // 绘制报告缩略图
      ctx.drawImage(reportCanvas, 0, 0);

      // 获取签名图片
      const signatureImage = new Image();
      if (this.photoForm.selectedPhotoUrl){
        signatureImage.src = this.photoForm.selectedPhotoUrl;

        await new Promise((resolve) => {
          signatureImage.onload = resolve;
        });

        // 设置签名图片的尺寸和位置
        const maxSignatureWidth = reportCanvas.width * 0.3; // 签名最大宽度为报告宽度的30%
        const maxSignatureHeight = reportCanvas.height * 0.3; // 签名最大高度为报告高度的30%

        // 计算签名图片的缩放比例，保持原始宽高比
        let scale = 1;
        if (signatureImage.width > maxSignatureWidth) {
          scale = maxSignatureWidth / signatureImage.width;
        }
        if (signatureImage.height * scale > maxSignatureHeight) {
          scale = maxSignatureHeight / signatureImage.height;
        }

        const signatureWidth = signatureImage.width * scale;
        const signatureHeight = signatureImage.height * scale;

        // 计算签名图片的位置（右下角）
        const x = reportCanvas.width - signatureWidth - 10; // 距离右边框10px
        const y = reportCanvas.height - signatureHeight - 10; // 距离下边框10px

        // 绘制签名图片到右下角
        ctx.drawImage(signatureImage, x, y, signatureWidth, signatureHeight);
      }


      // 添加边框（可选）
      // ctx.strokeStyle = '#000';
      // ctx.lineWidth = 1;
      // ctx.strokeRect(x, y, signatureWidth, signatureHeight);

      // 绘制医院 logo
      const logoImage = new Image();
      logoImage.src = process.env.VUE_APP_BASE_API + this.logo;

      await new Promise((resolve) => {
        logoImage.onload = resolve;
      });

      const logoWidth = 25; // logo 宽度
      const logoHeight = 25; // logo 高度
      const logoX = 10; // logo 距离左边框 10px
      const logoY = 10; // logo 距离上边框 10px

      ctx.drawImage(logoImage, logoX, logoY, logoWidth, logoHeight);

      // 绘制医院名字
      ctx.font = '16px Arial';
      ctx.fillStyle = '#000';
      ctx.fillText(this.hospitalName, logoX + logoWidth + 10, logoY + 20);

      this.reportImageUrl = combinedCanvas.toDataURL('image/png');

      const blob = await new Promise((resolve) => {
        combinedCanvas.toBlob((blob) => {
          resolve(blob);
        }, 'image/png', 0.8); // 0.8 是图片质量（0-1）
      });
      console.log(blob)

      // 7. 构造 FormData 并上传到 RuoYi
      const formData = new FormData();
      formData.append('file', blob, `儿童行为量表报告_${this.currentScaleScreenId}.png`);
      if (this.photoForm.selectedPhotoUrl){
        uploadPhoto(formData).then(res=>{
          console.log(res)
          if (res.code === 200) {
            this.$modal.msgSuccess("图片上传成功");
            console.log("服务器返回的文件路径:", res.fileName);
            const data = {
              scaleScreenId : this.currentScaleScreenId,
              remark : res.fileName
            }
            // 可以在这里将 res.fileName 存储到数据库
            updateScreen(data).then();
          } else {
            this.$modal.msgError(res.msg || "上传失败");
          }
        })
      }
    },
    // 子组件数据加载完成回调
    onDataReady() {
      this.isDataReady = true;
    },
    // 子组件渲染完成回调
    onRendered() {
      this.isRendered = true;
    },
    // 等待数据和渲染完成
    async waitForDataAndRender() {
      let attempts = 0;
      while (attempts < 10) { // 增加重试次数
        if (this.isDataReady && this.isRendered) {
          return true;
        }
        await new Promise(resolve => setTimeout(resolve, 200));
        attempts++;
      }
      throw new Error('等待数据加载和渲染超时');
    },
    downloadReport() {
      if (!this.reportImageUrl) return;
      const link = document.createElement('a');
      link.href = this.reportImageUrl;
      link.download = `儿童行为量表报告_${this.currentScaleScreenId}.png`;
      link.click();
      this.getList()
    },
    async checkTableRendered() {
      // 检查表格是否存在
      const tables = this.$el.querySelectorAll('.el-table');
      if (tables.length === 0) return false;
      // 检查表格行是否渲染
      return Array.from(tables).every(table => {
        return table.querySelectorAll('.el-table__row').length > 0;
      });
    },
    async conform1() {
      this.dialogVisible = false; // 关闭确认弹窗
      this.loading = true; // 显示全局加载状态
      try {
        // 1. 显示子组件并加载数据
        this.dialogVisible2 = true;
        await this.$refs.reportComponent.loadData(this.currentScaleScreenId);
        // 2. 等待子组件渲染完成
        let attempts = 0;
        while (attempts < 5) {
          await this.$nextTick();
          if (await this.$refs.reportComponent.checkTableRendered()) break;
          await new Promise(resolve => setTimeout(resolve, 300));
          attempts++;
        }
        // 3. 生成缩略图
        const canvas = await html2canvas(this.$refs.reportComponent.$el, {
          scale: 0.8,
          useCORS: true,
          backgroundColor: '#fff',
          logging: true // 调试用
        });
        // 4. 显示结果
        this.thumbnailUrl = canvas.toDataURL('image/png');
      } catch (error) {
        console.error('生成缩略图失败:', error);
        this.$message.error('生成缩略图失败');
      } finally {
        this.loading = false;
      }
    },
    toSignIndex(row){
      this.getPhoto()
      // 保存当前行的scaleScreenId
      this.currentScaleScreenId = row.scaleScreenId;
      this.dialogVisible = true
    },
    async generateReport() {
      this.dialogVisible = false;
      this.reportDialogVisible = true;
      this.generatingReport = true;
      try {
        // 1. 加载子组件数据
        await this.$refs.reportComponent.loadData(this.currentScaleScreenId);
        // 2. 等待渲染完成
        await this.waitForRender();
        // 3. 生成缩略图
        await this.generateThumbnail();
      } catch (error) {
        console.error('生成报告失败:', error);
        this.$message.error('生成报告失败: ' + error.message);
      } finally {
        this.generatingReport = false;
      }
    },
    uploadImg() {
      this.$refs.cropper.getCropBlob(data => {
        let formData = new FormData();
        formData.append("avatarfile", data, this.options.filename);
        uploadAvatar(formData).then(response => {
          this.open = false;
          this.options.img = process.env.VUE_APP_BASE_API + response.imgUrl;
          store.commit('SET_AVATAR', this.options.img);
          this.$modal.msgSuccess("修改成功");
          this.visible = false;
        });
      });
    },
    // 等待渲染完成
    async waitForRender() {
      let attempts = 0;
      while (attempts < 5) {
        await this.$nextTick();
        if (await this.$refs.reportComponent.checkTableRendered()) {
          return true;
        }
        await new Promise(resolve => setTimeout(resolve, 300));
        attempts++;
      }
      throw new Error('渲染超时');
    },
    selectScales(query){
      if (query) {
        const lowerQuery = query.toLowerCase();
        this.scaleBox = this.scales.filter(item =>
          item.scaleName.toLowerCase().includes(lowerQuery)
        );
      } else {
        // 搜索词为空时显示所有选项
        this.scaleBox = this.sca;
      }

    },
    selectPatient(query){
      if (query) {
        this.patientBox = this.patients.filter(item =>
          item.childName.toLowerCase().includes(query)
        );
      } else {
        // 搜索词为空时显示所有选项
        this.patientBox = this.pat;
      }

    },
    //查询量表列表
    getScales(){
      listScales().then(res=>{
        this.scales = res.rows;
        this.sca = this.scales.slice(0, 5);
        this.scaleBox = this.sca;
      });
    },
    //查询病患列表
    getPatients(){
      listPatients().then(res=>{
        this.patients = res.rows;
        this.pat = this.patients.slice(0, 5);
        this.patientBox = this.pat;
      });
    },
    //测评
    evaluation(row){
      // console.log(row)
      this.$router.push({path:'/CBCLForm',query:{row:row}});
    },
    //查看
    examine(row){
      console.log(row)
      this.$router.push({path:'/ResultForm',query:{row:row}})
    },
    /** 查询量表筛选列表 */
    getList() {
      this.loading = true;
      listScreen(this.queryParams).then(response => {
        this.screenList = response.rows;
        for (let i = 0;i< response.total;i++){
          if (response.rows[i].status ==  1){
            response.rows[i].status = "已完成"
          }else {
            response.rows[i].status = "未完成"
          }
        }
        this.total = response.total;
        this.loading = false;
      });
      // location.reload()
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        scaleScreenId: null,
        scaleId: null,
        scaleName: null,
        patientId: null,
        patientName: null,
        status: null,
        result: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.scaleScreenId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getScales();
      this.getPatients();
      this.reset();
      this.open = true;
      this.title = "添加量表筛选";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const scaleScreenId = row.scaleScreenId || this.ids
      getScreen(scaleScreenId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改量表筛选";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.scaleName = this.scales.find(item => item.scaleId === this.form.scaleId).scaleName;
      this.form.patientName = this.patients.find(item => item.patientId === this.form.patientId).childName;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.scaleScreenId != null) {
            updateScreen(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            insterScreen(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const scaleScreenIds = row.scaleScreenId || this.ids;
      this.$modal.confirm('是否确认删除量表筛选编号为"' + scaleScreenIds + '"的数据项？').then(function() {
        return delScreen(scaleScreenIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dcp/screen/export', {
        ...this.queryParams
      }, `screen_${new Date().getTime()}.xlsx`)
    },
    async showThumbnail() {
      this.loading = true;
      try {
        // 等待数据加载
        if (!this.$refs.reportComponent.isDataReady) {
          await new Promise(resolve => {
            this.$refs.reportComponent.$once('data-ready', resolve);
          });
        }

        // 等待表格渲染（最多重试5次）
        let attempts = 0;
        while (attempts < 5) {
          await this.$nextTick();
          if (await this.$refs.reportComponent.checkTableRendered()) break;
          await new Promise(resolve => setTimeout(resolve, 300));
          attempts++;
        }

        // 执行截图
        const canvas = await html2canvas(this.$refs.reportComponent.$el, {
          scale: 0.8,
          useCORS: true,
          backgroundColor: '#fff'
        });

        this.thumbnailUrl = canvas.toDataURL('image/png');
        this.dialogVisible = true;

      } catch (error) {
        console.error('生成缩略图失败:', error);
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style>
::v-deep .el-form-item__label{
  color:#4873ca;
}
::v-deep th{
  background-color: #4874cb !important;
  color: white !important;
}
</style>
